<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Provider\DispatchMessage;
use Base\BaseData;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Logger\LoggerFactory;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

class ServerController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    protected $logger;

    protected $disPatchMessage;

    public function __construct(LoggerFactory $loggerFactory, DispatchMessage $disPatchMessage)
    {
        $this->logger = $loggerFactory->get('server_controller');
        $this->disPatchMessage = $disPatchMessage;
    }

    public function onMessage($server, Frame $frame): void
    {
        $baseData = new BaseData();
        $res = base64_decode($frame->data);
        $baseData->mergeFromString((string) $res);
        $this->logger->info('request message', json_decode($baseData->serializeToJsonString(), true));
        $this->disPatchMessage->dispatch($baseData, $frame->fd);
    }

    public function onOpen($server, Request $request): void
    {
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
    }
}
